import { ElMessage } from 'cs-element-plus/es';
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { Ref } from 'vue'


export function isPrimative(val) {
  const isObject = ['Object', 'Array'].includes(
    Object.prototype.toString.call(val).slice(8, -1)
  )
  return !isObject
}

export const isPlainObject = (val) => {
  return Object.prototype.toString.call(val).slice(8, -1) === 'Object'
}

export const pickData = (data, keys, defVal = '') => {
  return keys.reduce((result, key) => {
    result[key] = data[key] === undefined ? defVal : data[key]
    return result
  }, {})
}

export const delArrayItems = (list:string[] = [], vals: string | string[] = []) => {
  if (!Array.isArray(vals)) {
    vals = [vals]
  }
  vals.forEach(val => {
    const index = list.findIndex(el => el === val)
    if (index >= 0) {
      list.splice(index, 1)
    }
  })
  return list
}


const getVueBuiltin = () => {
  const $store = useStore()
  const $router = useRouter()
  const $route = useRoute()
  const builtin = { $store, $router, $route, query: $route.query || {} }

  const get = () => builtin
  Object.assign(getVueBuiltin, { get })

  return builtin
}
getVueBuiltin.get = () => {
  const result = {} as ReturnType<typeof getVueBuiltin>
  console.warn('请先在setup中调用 vueBuiltin()')
  return result
}

export const vueBuiltin: typeof getVueBuiltin & { get: () => ReturnType<typeof getVueBuiltin> } = getVueBuiltin as any



export function formatDate(date = new Date(), sep = '-', withTime = true) {
  const d2 = val => ('00' + val).slice(-2)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const dateStr = [year, d2(month), d2(day)].join(sep)

  let result = dateStr
  if (withTime) {
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    const timeStr = [d2(hour), d2(minute), d2(second)].join(':')
    result += 'T' + timeStr
  }

  return result
}

export const parseJson = (data) => {
  if (typeof data !== 'string') return data
  const jsonRe = /^\[[\s\S]*\]$|^\{[\s\S]*\}$/
  try {
    if (jsonRe.test(data)) {
     data = JSON.parse(data)
    } else {
      ElMessage.warning('非json格式')
    }
  } catch (e: any) {
    ElMessage.warning('parseJson err' + e?.message)
  }

  return data
}


export const sleep = (seconds = 1) => {
  return new Promise(resolve => setTimeout(resolve, seconds * 1000))
}

// 把小数 或 可能带千分位的数字字符串 固定精度  如: val: 1,234.5678 => '1234.57'
export function numberFixed (val: string | number = '0', n = 2): number | string {
  const isNumber = typeof val === 'number'
  const numStr = (val + '').trim().replace(/,/g, '')
  const value = Number(numStr).toFixed(n)
  if (isNumber) return value

  const [intPart, floatPart = ''] = String(value).split('.')
  return thousandSeperatorBetter(intPart) + (floatPart ? `.${floatPart}` : '')
}

function thousandSeparator(num) {
  const reverse = str => String(str).split('').reverse().join('')
  return reverse(reverse(num).replace(/\d{3}(?!$)/g, '$&,'))
}

export function thousandSeperatorBetter(num) {
  return String(num).replace(/\d(?=(\d{3})+$)/g, '$&,')
}


export const uniqList = (list: any[] = [], idKey = '') => {
  if (list.every(el => !isPlainObject(el))) {
    return Array.from(new Set(list))
  }

  const idList: any[] = []
  const result: any[] = []
  list.forEach(el => {
    if (!idList.includes(el[idKey])) {
      idList.push(el[idKey])
      result.push(el)
    }
  })
  return result
}

export const renameKeys = (obj: object = {}, keyMapOrFn: object | ((key: string, val: any) => string)) => {
  const result = {}
  Object.keys(obj).forEach((key) => {
    let newKey = key
    if (typeof keyMapOrFn === 'function') {
      newKey = keyMapOrFn(key, obj[key]) || key
    } else {
      newKey = keyMapOrFn[key] || key
    }
    result[newKey] = obj[key]
  })

  return result
}
